from django.shortcuts import  get_object_or_404
from django.http import JsonResponse
from public.function import Public
from django.contrib.auth.models import User




class Menu_Mananger(Public):
    #重写update方法
    def update(self, *args, **kwargs):
        id = self.request.POST.get('id')
        server = get_object_or_404(self.models, id=id)
        menus_show = self.request.POST.get('menus_show').split(',') or None
        if menus_show:
            new_list = [int(x) for x in menus_show]
            new_list = set(new_list)  # 去重复
            new_menu_string = ",".join(str(x) for x in new_list)
            server.menus_show = new_menu_string
            server.save()
            return JsonResponse({'msg': "successful"},
                                safe=False)  # server.menus_show = str(list(dic['menus_show']).sort())
            # server.save()
        else:
            return JsonResponse({'msg': "failed"}, safe=False)

    #重写add 方法
    def add(self, *args, **kwargs):
        form = self.form(self.request.POST or None)

        # 判断form是否有效
        if form.is_valid():
            try:
                form.save()
                return JsonResponse({'msg': "post form data save successful"}, safe=False)
            except AttributeError as e:
                dic = {}
                for key in self.request.POST.keys():
                    value = self.request.POST.get(key)
                    dic[key] = value

                del dic['csrfmiddlewaretoken']
                userid = dic['user']
                userobj = User.objects.get(pk=userid)
                dic['user'] = userobj
                self.models.objects.create(**dic)
                return JsonResponse({'msg': "post form data save successful"}, safe=False)
            except Exception as e:
                return JsonResponse({'msg': str(e)}, safe=False)
        else:
            return JsonResponse({'msg': "post form data  vailadate failed %s" % str(form.errors)}, safe=False)



